#define _CRT_SECURE_NO_WARNINGS
#include "MedianFilter.h"
#include<iostream>
#include<Windows.h>

Matrix MedianFilter::Filtering(const Matrix& input)
{
	int height = input.Height();
	int width = input.Width();
	Matrix mtemp(height, width);
	int left, right, up, down;
	for (int i = 0;i < height;i++)
		for (int j = 0;j < width;j++)
		{

			left = j - filterSize / 2;
			if (left < 0)
				left = 0;
			right = j + filterSize / 2;
			if (right >= width)
				right = width - 1;
			up = i - filterSize / 2;
			if (up < 0)
				up = 0;
			down = i + filterSize / 2;
			if (down >= height)
				down = height - 1;
			int temp = left;
			int lenth = (right - left + 1) * (down - up + 1);
			double* Td = new double[lenth];
			int d = 0;
			for (up;up <= down;up++)
			{
				left = temp;
				for (left;left <= right;left++, d++)
					Td[d] = input.At(up, left);
			}
			for(int n=0;n< lenth;n++)
				for(int m=n+1;m<lenth;m++)
					if (Td[n] > Td[m])
					{
						double t = Td[n];
						Td[n] = Td[m];
						Td[m] = t;
					}
			mtemp.At(i,j) = Td[lenth/2];
			delete[]Td;
		}
	return mtemp;
}